import React, { useState, useEffect } from 'react';
import { Button, Input, Space, Popconfirm, message, Tag, Modal } from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  DeleteOutlined, 
  EditOutlined,
  BookOutlined,
  EyeOutlined,
  GlobalOutlined,
  LockOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { FilterCard, TableCard } from '@/components/common';
import { QuestionBank } from '@/types/question';
import { questionService } from '@/services/questionService';
import QuestionBankForm from './components/QuestionBankForm';

const QuestionBankList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [questionBanks, setQuestionBanks] = useState<QuestionBank[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingBank, setEditingBank] = useState<QuestionBank | null>(null);

  // 加载题库列表
  const fetchQuestionBanks = async (page = 1, keyword = '') => {
    setLoading(true);
    try {
      const response = await questionService.getQuestionBanks({
        page,
        limit: pagination.pageSize,
        keyword,
      });
      const data = response.data.data;
      setQuestionBanks(data.results);
      setPagination({
        ...pagination,
        current: page,
        total: data.count,
      });
    } catch (error) {
      message.error('获取题库列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchQuestionBanks(pagination.current, searchKeyword);
  }, []);

  // 搜索
  const handleSearch = () => {
    fetchQuestionBanks(1, searchKeyword);
  };

  // 新建题库
  const handleCreate = () => {
    setEditingBank(null);
    setModalVisible(true);
  };

  // 编辑题库
  const handleEdit = (bank: QuestionBank) => {
    setEditingBank(bank);
    setModalVisible(true);
  };

  // 删除题库
  const handleDelete = async (id: number) => {
    try {
      await questionService.deleteQuestionBank(id);
      message.success('删除成功');
      fetchQuestionBanks(pagination.current, searchKeyword);
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 查看题库详情（题目列表）
  const handleViewBank = (bank: QuestionBank) => {
    navigate(`/admin/question/bank/${bank.id}`);
  };

  // 保存题库
  const handleSave = async (values: Partial<QuestionBank>) => {
    try {
      if (editingBank) {
        await questionService.updateQuestionBank(editingBank.id, values);
        message.success('更新成功');
      } else {
        await questionService.createQuestionBank(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchQuestionBanks(pagination.current, searchKeyword);
    } catch (error) {
      message.error(editingBank ? '更新失败' : '创建失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '题库名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: QuestionBank) => (
        <Space>
          <BookOutlined />
          <a onClick={() => handleViewBank(record)}>{text}</a>
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '题目数量',
      dataIndex: 'question_count',
      key: 'question_count',
      width: 100,
      render: (count: number) => (
        <Tag color="blue">{count} 道</Tag>
      ),
    },
    {
      title: '可见性',
      dataIndex: 'is_public',
      key: 'is_public',
      width: 100,
      render: (isPublic: boolean) => (
        <Tag icon={isPublic ? <GlobalOutlined /> : <LockOutlined />} color={isPublic ? 'green' : 'default'}>
          {isPublic ? '公开' : '私有'}
        </Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: 'created_by_name',
      key: 'created_by_name',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: QuestionBank) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewBank(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此题库吗？"
            description="删除后题库中的题目仍会保留，但会失去题库归属"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <FilterCard
        pageTitle="题库管理"
        titleIcon={<BookOutlined />}
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建题库
          </Button>
        }
      >
        <Space>
          <Input
            placeholder="搜索题库名称或描述"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onPressEnter={handleSearch}
            prefix={<SearchOutlined />}
            style={{ width: 300 }}
          />
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
        </Space>
      </FilterCard>

      <TableCard
        tableProps={{
          columns,
          dataSource: questionBanks,
          rowKey: 'id',
          loading,
          pagination: {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: (page) => {
              setPagination({ ...pagination, current: page });
              fetchQuestionBanks(page, searchKeyword);
            },
          },
        }}
      />

      {/* 创建/编辑题库模态框 */}
      <Modal
        title={editingBank ? '编辑题库' : '新建题库'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <QuestionBankForm
          initialValues={editingBank || undefined}
          onSubmit={handleSave}
          onCancel={() => setModalVisible(false)}
        />
      </Modal>
    </div>
  );
};

export default QuestionBankList;

